package ru.nsu.ccfit.kalah.game;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Field {

    public static int PITS_COUNT = 14;
    public static int STONES_COUNT = 6;
    public static int NORTH_PLAYER_HOUSE = 7;
    public static int SOUTH_PLAYER_HOUSE = 0;
    protected int[] pits = new int[PITS_COUNT];


    private ObjectPool<int[]> fieldPool;
    private HistoryBuffer<int[]> historyBuffer;

    public Field() {
        Arrays.fill(pits, STONES_COUNT);
        pits[NORTH_PLAYER_HOUSE] = pits[SOUTH_PLAYER_HOUSE] = 0;
    }

    public Field(Field field) {
        System.arraycopy(field.pits, 0, pits, 0, pits.length);

    }


    public int get(int index) {
        return pits[index];
    }

    public void set(int index, int value) {
        pits[index] = value;
    }


    private ObjectPool<int[]> getFieldPool() {
        if (fieldPool == null) {
            fieldPool = new ObjectPool<int[]>(new ObjectPool.Creator<int[]>() {
                @Override
                public int[] newInstance() {
                    return new int[PITS_COUNT];
                }
            });
        }
        return fieldPool;
    }

    private HistoryBuffer<int[]> getHistoryBuffer() {
        if (historyBuffer == null) {
            historyBuffer = new HistoryBuffer<int[]>();
        }
        return historyBuffer;
    }

    protected void save() {
        int[] saved = getFieldPool().get();
        System.arraycopy(pits, 0, saved, 0, saved.length);
        getHistoryBuffer().push(saved);
    }

    protected void restore() {
        getFieldPool().put(pits);
        pits = getHistoryBuffer().pop();
    }

    @Override
    public String toString() {
        return "Field{" +
                Arrays.toString(pits) +
                '}';
    }
}
